package edu.xjtu.jih.item;

import edu.xjtu.jih.common.Result;
import edu.xjtu.jih.common.Utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.List;
import java.util.UUID;

@MultipartConfig //此注解表示可以接收上传文件
@WebServlet({
        "/item/getAllItem",
        "/item/getItem",
        "/item/addItem",
        "/item/delItem",
        "/item/changeItemInfo",
        "/item/avatar",//上传商品图片
})
public class ItemAPI extends HttpServlet {
    //该方法在Servlet初始化时执行，仅执行一次
    @Override
    public void init() throws ServletException {
        File dir = new File(ItemDto.AVATAR_DIR);//表示文件或目录的路径
        if(!dir.exists()){//目录不存在则创建
            dir.mkdirs();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ItemService itemService=new ItemService();
        req.setCharacterEncoding("UTF-8");
        String path=req.getServletPath();

        if ("/item/getAllItem".equals(path)){
            ItemDto dto = Utils.getBeanFromRequest(ItemDto.class,req);

            List<ItemDto> itemList =  itemService.getAllItem(dto);
            //通过视图生成json
            Utils.outResult(resp, Result.success(itemList));
        }

        if("/item/avatar".equals(path)){
            //从请求参数中通过参数名称filename获取文件名称
            String filename = req.getParameter("filename");
            //读取文件的输入流
            InputStream in = new FileInputStream(ItemDto.AVATAR_DIR+"/"+filename);
            //将文件信息输出到浏览器的输出流
            OutputStream out = resp.getOutputStream();

            byte[] b = new byte[10240];//容量为10240字节的缓存区
            int len = -1;//从输入流读取并放入缓存区的数据量

            while((len=in.read(b))!=-1){
                out.write(b,0,len);
            }
            out.flush();
            out.close();
            in.close();

        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        ItemService itemService=new ItemService();
        req.setCharacterEncoding("UTF-8");
        String path=req.getServletPath();

        if ("/item/addItem".equals(path)){
            ItemDto dto = Utils.getBeanFromRequest(ItemDto.class,req);
            int succ= itemService.addItem(dto);
            if (succ==1){
                Utils.outJson(resp, Result.success());
            }else{
                Utils.outJson(resp, Result.fail(Result.ERR_CODE_BUSINESS,"请登录后重试"));
            }
        }

        if ("/item/delItem".equals(path)){
            ItemDto dto = Utils.getBeanFromRequest(ItemDto.class,req);

            int succ = itemService.delItem(dto.getItem_id());//1删除成功,0不成功

            if (succ==1){
                Utils.outResult(resp, Result.success("删除成功",succ));
            }else{
                Utils.outResult(resp, Result.success("未查找到该商品信息",succ));
            }
        }

        if ("/item/getItem".equals(path)){
            ItemDto dto = Utils.getBeanFromRequest(ItemDto.class,req);
            ItemDto itemInfo= itemService.getItem(dto);

            //通过视图生成json
            Utils.outResult(resp, Result.success(itemInfo));
        }

        if ("/item/changeItemInfo".equals(path)){
            ItemDto dto = Utils.getBeanFromRequest(ItemDto.class,req);
            itemService.changeItemInfo(dto);

            System.out.println(dto.getItem_id());
            //通过视图生成json
            Utils.outResult(resp, Result.success());
        }

        if("/item/avatar".equals(path)){
            Part part = req.getPart("avatar");

            InputStream in = part.getInputStream();

            String name = UUID.randomUUID().toString();//获得通过uuid算法得到的不重复的字符串
            String submitedFilename = part.getSubmittedFileName();//原始文件名
            String suffix = submitedFilename.substring(submitedFilename.lastIndexOf("."));
            String filename = name+suffix;
            OutputStream out = new FileOutputStream(ItemDto.AVATAR_DIR+"/"+filename);

            byte[] b = new byte[10240];//容量为10240字节的缓存区
            int len = -1;//从输入流读取并放入缓存区的数据量

            while((len=in.read(b))!=-1){
                out.write(b,0,len);
            }
            out.flush();
            out.close();
            in.close();

//            CurrentUser currentUser = (CurrentUser)request.getSession().getAttribute(CurrentUser.SESSION_ATTR_NAME);
//            service.setAvatar(currentUser,filename);

            Utils.outResult(resp, Result.success("提交成功",filename));//将filename返回
        }

    }
}
